package com.example.singleton.lazy;

import java.util.concurrent.CountDownLatch;

/**
 * 懒汉式单例（延时加载）
 * <p>
 * 先静态、后动态
 * 先属性、后方法
 * 先上后下
 */
public class LazyDoubleCheckSingleton {

    private LazyDoubleCheckSingleton() { }

    private static LazyDoubleCheckSingleton instance;

    public static LazyDoubleCheckSingleton getInstance() {
        if (instance == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (instance == null) {
                    instance = new LazyDoubleCheckSingleton();
                }
            }
        }
        return instance;
    }


    public static void main(String[] args) {

        int count = 100;
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                    System.out.println(System.currentTimeMillis() + " " + LazyDoubleCheckSingleton.getInstance());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            latch.countDown();
        }

    }

}
